#include "schedulethread.h"
#include "os_dependence.h"


ScheduleThread::ScheduleThread(QObject *parent) :
    QThread(parent),
    waits_cnt(0)
{
    finish = false;
    start(QThread::LowestPriority);
}


ScheduleThread::~ScheduleThread()
{
    finish = true;

    wait_cond.wakeOne();
    //terminate();
    wait();
}


void ScheduleThread::run()
{

    while(!finish)
    {
        if(waits_cnt < 1)
            wait_cond.wait(&wait_mutex);

        mutex.lock();
        bool lock = objects.isEmpty();
        mutex.unlock();

        if(lock) {
            //QSleep::_usleep(500);
            continue;
        }

        mutex.lock();
        ScheduleObject obj = objects.dequeue();
        --waits_cnt;
        mutex.unlock();

        qWarning() << "Run func";
        ((void (*)(void*, void*, void*))obj._func)(obj._args[0], obj._args[1], obj._args[2]);
        qWarning() << "Run Done";
    }
}


void ScheduleThread::schedule(void *func, void *p1, void *p2, void *p3)
{
    if(!isRunning())
        start();

    qWarning() << "schedule";
    mutex.lock();
    objects.enqueue(ScheduleObject(func, p1, p2, p3));
    ++waits_cnt;
    mutex.unlock();
    qWarning() << "Sched Done";

    wait_cond.wakeOne();
}


void ScheduleThread::waitForFinished()
{
    wait();
}
